package com.rogerfan.easy.shiro.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.rogerfan.easy.shiro.ShiroTokenManager;
import com.rogerfan.easy.shiro.ShiroUtils;
import com.rogerfan.easy.web.util.WebUtil;

@Component
public class AppAuthenticationFilter extends FormAuthenticationFilter{

	
	private Logger log = LoggerFactory.getLogger(getClass());
	
	public static String HEADER_LOGIN_NAME="SHIRO-LOGIN";
	@Autowired
	ShiroTokenManager tokenManager;
	
	@Override
	protected boolean onAccessDenied(ServletRequest request,
			ServletResponse response) throws Exception {
		//这里只配置登录地址使用这个过滤器
		if (isLoginRequest(request, response)) {
			if (isLoginSubmission(request, response)) {
				return executeLogin(request, response);
			} else {
				return true;
			}
		} else {
			
			if (!WebUtil.isAjaxRequest(request)){
				  saveRequestAndRedirectToLogin(request, response);
			} else {
				WebUtil.print(response, WebUtil.loginError);
			}
			return false;
		}
	}

	@Override
	protected boolean onLoginSuccess(AuthenticationToken token,
			Subject subject, ServletRequest request, ServletResponse response)
			throws Exception {
		AppUserNameToken _token=(AppUserNameToken)token;
		String loginHeader =WebUtil.getHeader(ShiroUtils.getRequest(), HEADER_LOGIN_NAME);
		//form 
		if(StringUtils.isBlank(loginHeader)){
			_token.setAppLogin(false);
			return super.onLoginSuccess(token, subject, request, response);
		}else{
			String gtoken =tokenManager.saveToken(ShiroUtils.getSession().getId().toString());
			_token.setToken(gtoken);
			_token.setAppLogin(true);
			return true;
		}
		
	}

	@Override
	protected boolean onLoginFailure(AuthenticationToken token,
			AuthenticationException e, ServletRequest request,
			ServletResponse response) {
		if (!WebUtil.isAjaxRequest(request)){
			return super.onLoginFailure(token, e, request, response);
		} else {
			try {
				WebUtil.print(response, WebUtil.loginError);
			} catch (IOException e1) {
				
			}
			return false;
		}
		
	}

	@Override
	protected AuthenticationToken createToken(String username, String password,
            boolean rememberMe, String host)  {
		
		return new AppUserNameToken(username,password,rememberMe,host);
	}
	
}
